import React, { PureComponent } from 'react';
import { isduplicate } from '@/services/department';
import { Form, Input, Select } from 'antd';

const { Option } = Select;

export default class Index extends PureComponent {

  checkUserNameUnique(rule, value, callback) {
    const { currentUnit = {} } = this.props;
    isduplicate({ dept_name: value, unit_id: currentUnit.id }).then(function (response) {
      if (response && response.status == 200) {
        const { result } = response;
        if ( result == 0) {
          callback();
        } else {
          callback('部门名称已存在');
        }
      } else {
        callback('校验部门名称失败!');
      }
    });
  }

  render() {
    const { form, constants = {}, data = {}, currentUnit = {}, disabled = false } = this.props;
    const { getFieldDecorator } = form;
    const { unit_id = {} } = data;

    return (
      <Form layout='vertical'>
        <Form.Item label='部门名称'>
          {getFieldDecorator('dept_name', {
            initialValue: data.dept_name || undefined,
            validateFirst: true,
            validateTrigger: 'onBlur',
            rules: [
              { required: true, message: '该项为必填项' },
              {
                validator: (rule, value, callback) =>
                  this.checkUserNameUnique(rule, value, callback),
              },
            ]
          })(
            <Input placeholder='请输入部门名称' size='large' disabled={disabled} />
          )}
        </Form.Item>
        <Form.Item label='单位名称'>
          {getFieldDecorator('unit_id.id', {
            initialValue: unit_id.id || currentUnit.id > 0 ? currentUnit.id : undefined,
            rules: [{ required: true, message: '该项为必填项' }],
          })(
            <Select placeholder='请选择单位' size='large' disabled={disabled}>
              {currentUnit.id > 0 && <Option value={currentUnit.id}>{currentUnit.unit_name}</Option>}
            </Select>
          )}
        </Form.Item>
      </Form>
    );
  }
}